/*
 * 精彩绘本抢先看编辑 
 */
import * as React from 'react';
import { connect } from 'react-redux';
import { find, filter, map, get, includes } from 'lodash';
import ReactCustomScrollBars from 'react-custom-scrollbars';
import {
  Affix,
  Card,
  Button,
  Divider,
  message,
  Modal,
  Spin,
  Switch,
  Icon,
  Dropdown,
  Menu,
  Row,
  Col,
} from 'antd';

import { isLoading, isEqualWithNumber } from 'utils/utils';
import ACTIONS from 'constants/preview';

import {
  fetchPreviewList,
  publishPreview,
  createPreview,
  updatePreview,
  removePreview,
} from 'actions/preview';
import './Index.scss';

import LoadableComponent from 'components/common/LoadableComponent';
const LoadablePreviewPageList = LoadableComponent(() => import('pages/preview/PageIndex'));
const LoadablePreviewEdit = LoadableComponent(() => import('./EditForm'));
const LoadableCustomModal = LoadableComponent(() => import('components/common/CustomModal'));

interface PreviewIndexProps {
  dispatch: (action: any) => any;
  previewList: any[];
  loadingGroup: any;
}

interface PreviewIndexState {
  selectPreviewId: any;
  editPreview: any;
}

class PreviewIndex extends React.Component<PreviewIndexProps, PreviewIndexState> {
  static DIFFICULTY_LEVEL = [
    {
      code: 0,
      desc: '容易',
    },
    {
      code: 1,
      desc: '困难',
    },
  ];
  static defaultProps: PreviewIndexProps = {
    dispatch: () => {},
    previewList: [],
    loadingGroup: {},
  };
  constructor(props: PreviewIndexProps) {
    super(props);

    this.state = {
      selectPreviewId: null,
      editPreview: null,
    };
  }

  availableLevels = () => {
    const { previewList } = this.props;
    const usedLevels = map(previewList, (item: any) => {
      return item.level;
    });
    return filter(PreviewIndex.DIFFICULTY_LEVEL, (item: any) => {
      return !includes(usedLevels, item.code);
    });
  };

  getLevelDesc = (code: number) => {
    const item = find(PreviewIndex.DIFFICULTY_LEVEL, (item: any) => {
      return item.code === code;
    });
    return get(item, 'desc', 'code异常');
  };

  componentDidMount() {
    this.handleFetchPreviewList();
  }

  handleFetchPreviewList() {
    this.props.dispatch(fetchPreviewList());
  }

  handleEditPreview = (editPreview: any = 0) => {
    this.setState({
      editPreview,
    });
  };

  handleSelectPreview = (selectPreviewId: any = 0) => {
    this.setState({
      selectPreviewId,
    });
  };

  handleSubmit = (values: Record<string, any>) => {
    const { dispatch } = this.props;
    const { editPreview } = this.state;
    const action = editPreview ? updatePreview(editPreview.id, values) : createPreview(values);
    dispatch(action).then((result: any) => {
      if (result.code) {
        message.error(result.msg);
      } else {
        message.success('保存成功');

        this.handleFetchPreviewList();
        this.setState({
          selectPreviewId: get(result, 'response.data.id', 0),
          editPreview: null,
        });
      }
    });
  };

  handleRemove = (previewId: number) => {
    const { dispatch } = this.props;

    Modal.confirm({
      title: '危险，慎重操作',
      content: '你确定要删除此绘本抢先看吗？',
      okText: '确定',
      cancelText: '取消',
      iconType: 'info-circle',
      onOk: () => {
        dispatch(removePreview(previewId)).then((result: any) => {
          if (result.code) {
            message.error(result.msg);
          } else {
            message.success('删除成功');

            this.handleFetchPreviewList();
          }
        });
      },
    });
  };

  handlePublish = (previewId: number, checked: boolean) => {
    const { dispatch, loadingGroup } = this.props;
    if (isLoading(loadingGroup, ACTIONS.PUBLISH)) {
      return;
    }

    const status = Number(checked);
    const content = checked ? '发布绘本抢先看' : '下线此绘本抢先看';
    Modal.confirm({
      title: '危险，慎重操作',
      content,
      okText: '确定',
      cancelText: '取消',
      iconType: 'info-circle',
      onOk: () => {
        dispatch(publishPreview(previewId, status)).then((result: any) => {
          if (result.code) {
            message.error(result.msg);
          } else {
            message.success('操作成功');

            this.handleFetchPreviewList();
          }
        });
      },
    });
  };

  render() {
    const { selectPreviewId, editPreview } = this.state;
    const { loadingGroup, previewList } = this.props;

    let menuItems = [];
    if (previewList.length > 0) {
      menuItems.push(
        <Menu
          key="data"
          mode="inline"
          selectedKeys={[String(selectPreviewId)]}
          onSelect={(item: any) => {
            this.handleSelectPreview(item['key']);
          }}>
          {previewList.map((item: any, index: number) => {
            const actions = [
              <Icon
                style={{ color: '#22c920' }}
                type="edit"
                onClick={(e: any) => {
                  e.stopPropagation();
                  this.handleEditPreview(item);
                }}
              />,
              <Icon
                style={{ color: '#f04134' }}
                type="delete"
                onClick={(e: any) => {
                  e.stopPropagation();
                  this.handleRemove(item.id);
                }}
              />,
              <div
                onClick={(e: any) => {
                  e.stopPropagation();
                }}>
                <Switch
                  loading={isLoading(loadingGroup, ACTIONS.PUBLISH)}
                  checked={Boolean(get(item, 'isPublished', 0))}
                  onChange={(checked: boolean) => {
                    this.handlePublish(item.id, checked);
                  }}
                />
              </div>,
            ];
            const avatar = <img src={item.cover.uri} width="60" />;
            return (
              <Menu.Item key={item.id} className="list-item">
                <Card key={index} className="card-box" actions={actions}>
                  <Card.Meta
                    avatar={avatar}
                    description={item.name}
                    style={{ display: 'flex', alignItems: 'center' }}
                  />
                  <div className="item-mark">{this.getLevelDesc(item.level)}</div>
                </Card>
              </Menu.Item>
            );
          })}
        </Menu>
      );
    }

    if (previewList.length < PreviewIndex.DIFFICULTY_LEVEL.length) {
      menuItems.push(
        <p key="action" className="loading-placeholder">
          <a
            href="javascript:void(0)"
            onClick={(e: any) => {
              e.preventDefault();
              this.handleEditPreview(0);
            }}>
            <Icon type="plus" />&nbsp; 添加
          </a>
        </p>
      );
    }

    return (
      <div id="panel_content-preview">
        <Row>
          <Col span={5}>
            <ReactCustomScrollBars
              id="preview_list_side"
              className="scroll-bar"
              autoHide={true}
              autoHeight={false}
              autoHideTimeout={600}
              autoHideDuration={400}>
              <div className="panel-content">
                <Spin spinning={isLoading(loadingGroup, ACTIONS.FETCH_LIST)}>{menuItems}</Spin>
              </div>
            </ReactCustomScrollBars>
          </Col>
          {selectPreviewId !== null && (
            <Col span={19}>
              <div id="preview_edit_side">
                <LoadablePreviewPageList previewId={selectPreviewId} />
              </div>
            </Col>
          )}
        </Row>
        {editPreview !== null && (
          <LoadableCustomModal
            title={editPreview === 0 ? '新增绘本抢先看' : '编辑绘本抢先看'}
            footer={false}
            onCancel={() => {
              this.handleEditPreview(null);
            }}>
            <LoadablePreviewEdit
              availableLevels={this.availableLevels()}
              allLevels={PreviewIndex.DIFFICULTY_LEVEL}
              editPreview={editPreview}
              onSubmit={this.handleSubmit}
            />
          </LoadableCustomModal>
        )}
      </div>
    );
  }
}

function mapStateToProps(state: any) {
  const { loadingGroup } = state;
  const { previewList } = state.preview;

  return {
    loadingGroup,
    previewList,
  };
}
export default connect(mapStateToProps)(PreviewIndex);
